package com.cool.apigateway.handler;

import com.cool.common.exception.BusinessException;
import com.cool.common.model.response.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ResponseResult<?> handleBusinessException(BusinessException ex) {
        logger.error("业务异常: code={}, message={}", ex.getErrorCode(), ex.getErrorMessage(), ex);
        return ResponseResult.fail(ex.getErrorCode(), ex.getErrorMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<?> handleGeneralException(Exception ex) {
        logger.error("系统异常: {}", ex.getMessage(), ex);
        return ResponseResult.fail("5000", "系统内部错误，请稍后重试");
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<?> handleIllegalArgumentException(IllegalArgumentException ex) {
        logger.error("参数异常: {}", ex.getMessage(), ex);
        return ResponseResult.fail("1001", ex.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<?> handleRuntimeException(RuntimeException ex) {
        logger.error("运行时异常: {}", ex.getMessage(), ex);
        return ResponseResult.fail("5000", "系统繁忙，请稍后重试");
    }
}
